package org.xtxg;

import java.net.InetSocketAddress;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.CharsetUtil;

/**
 * Hello world!
 *
 */
public class HelloWorldServer
{
    final int port; // 设置服务端口

    public HelloWorldServer(int port) {
        this.port = port;
    }

    /**
     * 引导服务器编写
     * @param args
     */
    public static void main( String[] args ) throws InterruptedException {
        System.out.println( "Hello World!" );
        new HelloWorldServer(1314).start(); // 调用start()方法

    }

    /**
     * 启动方法编写
     */
    private void start() throws InterruptedException {
//        final EchoServerHandler serverHandler = new Echo
        EventLoopGroup group = new NioEventLoopGroup(); // 1.创建EventLoopGroup对象
        try {
            ServerBootstrap bootstrap = new ServerBootstrap(); // 2.创建BootStrap
            bootstrap.group(group)
                    .channel(NioServerSocketChannel.class) // 3.指定NIO方式传输Channel
                    .localAddress(new InetSocketAddress(port)) // 4.使用指定的端口设置套接字地址
                    .childHandler(new ChannelInitializer<SocketChannel>() { // 添加一个EchoServerHandle到Channel的ChannelPipline

                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() { // 使用匿名类执行业务
                                @Override
                                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                    ByteBuf in = (ByteBuf) msg;
                                    System.out.println("服务端接收到信息 " + in.toString(CharsetUtil.UTF_8));// 将消息记录到控制台

                                    ctx.write(in); // 将接受到信息写个发送者，而不冲刷出站消息
                                }

                                @Override
                                public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
                                    ctx.writeAndFlush(Unpooled.EMPTY_BUFFER);
//                                            .addListener(ChannelFutureListener.CLOSE);// 将未决信息冲刷至远程节点，并且关闭Channel
                                }

                                @Override
                                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                                    cause.printStackTrace();// d打印异常栈
                                    ctx.close();// 关闭Channel
                                }
                            });
                        }
                    });
            ChannelFuture future = bootstrap.bind().sync();// 6.异步绑定服务器；调用sync（）方法阻塞等待直到绑定完成
            future.channel().closeFuture().sync();// 7.获取Channel的CloseFuture，并且阻塞当前线程直到它完成
        } finally {
            group.shutdownGracefully().sync(); // 8.关闭EventGroup，释放所有的资源
        }
    }


}
